package com.xmall.timer.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmall.define.dto.log.RetryLogDto;
import com.xmall.define.dto.log.RetryLogTimerTaskDto;
import com.xmall.define.request.sys.RetryLogListPageQueryRequest;
import com.xmall.timer.dto.TimerTaskDto;
import com.xmall.timer.handler.IRetryLogTaskHandler;
import com.xmall.timer.handler.ITimerTaskHandler;
import com.xmall.timer.manager.TimerTaskManager;
import com.xmall.timer.service.ICommonRetryLogTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommonRetryLogTaskServiceImpl implements ICommonRetryLogTaskService {

    @Resource
    private TimerTaskManager timerTaskManager;

    /**
     * 任务列表
     */
    @Override
    public List<RetryLogTimerTaskDto> taskList() {
        List<TimerTaskDto> taskList = timerTaskManager.taskList(IRetryLogTaskHandler.class);
        return taskList.stream().map(task -> {
            RetryLogTimerTaskDto dto = new RetryLogTimerTaskDto();
            BeanUtils.copyProperties(task, dto);

            ITimerTaskHandler taskHandler = timerTaskManager.getTaskHandler(task.getKey());
            if(null != taskHandler) {
                dto.setHasLogException(((IRetryLogTaskHandler)taskHandler).hasException());
            }
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 日志分页列表
     */
    @Override
    public Page<RetryLogDto> logListPage(Integer page, Integer pageSize, String key) {
        ITimerTaskHandler taskHandler = timerTaskManager.getTaskHandler(key);
        if(null != taskHandler) {
            IRetryLogTaskHandler retryLogTaskHandler = (IRetryLogTaskHandler) taskHandler;

            RetryLogListPageQueryRequest request = new RetryLogListPageQueryRequest();
            request.setPage(page);
            request.setPageSize(pageSize);
            return retryLogTaskHandler.retryListPage(request);
        }
        return new Page<>();
    }
}
